package com.uni.web.util;

import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uni.common.util.HttpClientUtil;

@Component
public class WechatUtil {

	public static String appid;
	
	public static String secret;
	
	public static String mchId;
	
	public static String key;
	
	public static String fwsappid;
	
	public static String fwsmchId;
	
	public static String returnUrl;
	
	public static String notifyUrl;
	
	public static String refundNotifyUrl;
	
	@Value("${wechat.appid}")
	public void setAppid(String appid) {
		WechatUtil.appid = appid;
	}
	
	@Value("${wechat.secret}")
	public void setSecret(String secret) {
		WechatUtil.secret = secret;
	}
	
	@Value("${wechat.mchId}")
	public void setMchId(String mchId) {
		WechatUtil.mchId = mchId;
	}
	
	@Value("${wechat.fwsappid}")
	public void setFwsappid(String fwsappid) {
		WechatUtil.fwsappid = fwsappid;
	}
	
	@Value("${wechat.fwsmchId}")
	public void setFwsmchId(String fwsmchId) {
		WechatUtil.fwsmchId = fwsmchId;
	}
	
	@Value("${wechat.key}")
	public void setKey(String key) {
		WechatUtil.key = key;
	}
	
	@Value("${wechat.returnUrl}")
	public void setReturnUrl(String returnUrl) {
		WechatUtil.returnUrl = returnUrl;
	}
	
	@Value("${wechat.notifyUrl}")
	public void setNotifyUrl(String notifyUrl) {
		WechatUtil.notifyUrl = notifyUrl;
	}
	
	@Value("${wechat.refundNotifyUrl}")
	public void setRefundNotifyUrl(String refundNotifyUrl) {
		WechatUtil.refundNotifyUrl = refundNotifyUrl;
	}
	
	/**
	 * @param code
	 * @return {"session_key":"TxR+vaoT53kwUnWD6TwnDw==","openid":"obYgv5TXlsNbBYjDvC2q5nGZf5JE"}
	 */
	public static String getSessionKeyOropenid(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret="
				+ secret + "&js_code=" + code + "&grant_type=authorization_code";
		
		String result = HttpClientUtil.doGet(url);
		return result;
	}
	
	public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
		// 被加密的数据
		byte[] dataByte = Base64.decode(encryptedData);
		// 加密秘钥
		byte[] keyByte = Base64.decode(sessionKey);
		// 偏移量
		byte[] ivByte = Base64.decode(iv);
		try {
			// 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
			int uni = 16;
			if (keyByte.length % uni != 0) {
				int groups = keyByte.length / uni + (keyByte.length % uni != 0 ? 1 : 0);
				byte[] temp = new byte[groups * uni];
				Arrays.fill(temp, (byte) 0);
				System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
				keyByte = temp;
			}
			// 初始化
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, "UTF-8");
				return JSON.parseObject(result);
			}
		} catch (Exception e) {
		}
		return null;
	}
	
//	appid: wx8fdf16e80de1b1ff
//    secret: 565ed5808e99d8c6ebd99a72f4c3031a
	public static void main(String[] args) {
		System.out.println(getSessionKeyOropenid("021lwNqT0jLf5Z1q03rT0R2TqT0lwNqb"));
	}
}
